const { getApiUrl } = require('../../config/config')
const { formatTime, formatDate } = require('../../utils/util')

Page({
  data: {
    currentTab: 0, // 0: 全部, 1: 赞, 2: 收藏
    days: 'null', // 默认查询全部历史数据
    pageSize: 10,
    currentPage: 1,
    interactions: {
      likes: [],
      collects: [],
      likesTotal: 0,
      collectsTotal: 0
    },
    isLoading: false,
    hasMore: true,
    userId: null,
    dayOptions: [
      { value: 'null', text: '全部' },
      { value: '7', text: '最近7天' },
      { value: '30', text: '最近30天' },
      { value: '90', text: '最近90天' }
    ],
    showFilter: false,
    dayFilterText: '全部',
    refreshing: false,
    animationData: {},
    combinedInteractions: [] // 新增：合并后的互动数据
  },

  onLoad: function() {
    // 设置导航栏透明
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#4a8eff'
    });
    
    // 初始化动画实例
    this.animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease',
    });
    
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userId: userInfo.id });
      this.fetchInteractions();
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.redirectTo({ url: '/pages/login/login' });
          }, 1500);
        }
      });
    }
  },

  onShow: function() {
    // 如果页面展示，检查是否需要重新加载数据
    if (this.data.needRefresh) {
      this.resetAndFetch();
      this.setData({ needRefresh: false });
    }
  },

  onPullDownRefresh: function() {
    this.setData({ refreshing: true });
    
    // 创建下拉刷新动画效果
    setTimeout(() => {
      this.resetAndFetch();
      setTimeout(() => {
        this.setData({ refreshing: false });
        wx.stopPullDownRefresh();
      }, 600);
    }, 800);
  },

  onReachBottom: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      // 显示加载更多的动画
      this.loadMoreData();
    }
  },

  // 页面点击事件，用于关闭筛选框
  onTap: function() {
    if (this.data.showFilter) {
      this.setData({ showFilter: false });
    }
  },

  // 切换标签
  switchTab: function(e) {
    const tab = parseInt(e.currentTarget.dataset.index);
    if (tab === this.data.currentTab) return;
    
    this.animation.opacity(0).step();
    this.setData({
      animationData: this.animation.export()
    });
    
    setTimeout(() => {
      this.setData({ 
        currentTab: tab,
        currentPage: 1,
        hasMore: true
      });
      
      // 更新合并后的数据
      const combinedInteractions = this.generateCombinedInteractions();
      this.setData({ combinedInteractions });
      
      this.animation.opacity(1).step();
      this.setData({
        animationData: this.animation.export()
      });
    }, 200);
  },

  // 显示/隐藏筛选选项
  toggleFilter: function() {
    this.setData({
      showFilter: !this.data.showFilter
    });
  },

  // 选择天数筛选
  selectDayFilter: function(e) {
    const { value, text } = e.currentTarget.dataset;
    if (value === this.data.days) {
      this.setData({ showFilter: false });
      return;
    }
    
    this.setData({
      days: value,
      dayFilterText: text,
      showFilter: false
    });
    
    // 添加一个轻微的触感反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'light' });
    }
    
    this.resetAndFetch();
  },

  // 重置并重新加载数据
  resetAndFetch: function() {
    this.setData({
      currentPage: 1,
      hasMore: true,
      interactions: {
        likes: [],
        collects: [],
        likesTotal: 0,
        collectsTotal: 0
      },
      combinedInteractions: []
    });
    this.fetchInteractions();
  },

  // 加载更多数据
  loadMoreData: function() {
    if (!this.data.hasMore || this.data.isLoading) return;
    
    const nextPage = this.data.currentPage + 1;
    this.setData({
      currentPage: nextPage
    });
    this.fetchInteractions();
  },

  // 获取互动数据
  fetchInteractions: function() {
    const { userId, days, currentPage, pageSize, currentTab } = this.data;

    if (!userId) return;

    this.setData({ isLoading: true });

    wx.request({
      url: getApiUrl('/message/interactions'),
      method: 'GET',
      data: {
        userId: userId,
        days: days === 'null' ? null : days,
        page: currentPage,
        size: pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newData = res.data.data;
          
          // 处理日期显示
          if (newData.likes) {
            newData.likes.forEach((item, index) => {
              // 确保每个item都有唯一ID
              item.id = item.id || `like_${Date.now()}_${index}`;
              item.formattedDate = this.getDisplayDate(item.createTime);
              item.formattedTime = this.getSimpleDate(item.createTime);
              item.isNew = this.isNewInteraction(item.createTime);
            });
          }
          
          if (newData.collects) {
            newData.collects.forEach((item, index) => {
              // 确保每个item都有唯一ID
              item.id = item.id || `collect_${Date.now()}_${index}`;
              item.formattedDate = this.getDisplayDate(item.createTime);
              item.formattedTime = this.getSimpleDate(item.createTime);
              item.isNew = this.isNewInteraction(item.createTime);
            });
          }
          
          // 合并数据
          let updatedInteractions;
          if (this.data.currentPage === 1) {
            // 首次加载
            updatedInteractions = newData;
          } else {
            // 加载更多，合并数据
            // 防止数据重复，先过滤掉已有的数据
            const existingLikeIds = new Set(this.data.interactions.likes.map(item => item.id));
            const existingCollectIds = new Set(this.data.interactions.collects.map(item => item.id));
            
            const newLikes = newData.likes.filter(item => !existingLikeIds.has(item.id));
            const newCollects = newData.collects.filter(item => !existingCollectIds.has(item.id));
            
            updatedInteractions = {
              likes: [...this.data.interactions.likes, ...newLikes],
              collects: [...this.data.interactions.collects, ...newCollects],
              likesTotal: newData.likesTotal,
              collectsTotal: newData.collectsTotal
            };
          }
          
          // 检查是否还有更多数据可加载
          const hasMore = (currentTab === 0 || currentTab === 1) && newData.likes.length === pageSize ||
                         (currentTab === 0 || currentTab === 2) && newData.collects.length === pageSize;
          
          this.setData({
            interactions: updatedInteractions,
            hasMore: hasMore
          }, () => {
            // 更新合并的数据
            const combinedInteractions = this.generateCombinedInteractions();
            this.setData({ combinedInteractions });
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('Failed to fetch interactions:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },
  
  // 检查是否为新互动（24小时内）
  isNewInteraction: function(dateString) {
    if (!dateString) return false;
    const now = new Date();
    const date = new Date(dateString);
    const diff = now - date;
    return diff < 86400000; // 24小时内
  },

  // 获取简单日期显示（YYYY-MM-DD）
  getSimpleDate: function(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return formatDate(date);
  },

  // 获取友好的日期显示格式
  getDisplayDate: function(dateString) {
    const today = new Date();
    const date = new Date(dateString);
    
    // 检查是否是今天
    if (
      date.getDate() === today.getDate() &&
      date.getMonth() === today.getMonth() &&
      date.getFullYear() === today.getFullYear()
    ) {
      // 如果是今天，显示具体时间
      const hours = date.getHours();
      const minutes = date.getMinutes();
      return `今天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
    }
    
    // 检查是否是昨天
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    if (
      date.getDate() === yesterday.getDate() &&
      date.getMonth() === yesterday.getMonth() &&
      date.getFullYear() === yesterday.getFullYear()
    ) {
      return '昨天';
    }
    
    // 检查是否是本周
    const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const dayDiff = Math.floor((today - date) / (24 * 60 * 60 * 1000));
    if (dayDiff < 7) {
      return dayOfWeek[date.getDay()];
    }
    
    // 其他情况，返回年月日
    return formatDate(date);
  },

  // 标记所有互动为已读
  markAllAsRead: function() {
    if (!this.data.interactions.likes.length && !this.data.interactions.collects.length) {
      return;
    }
    
    wx.showModal({
      title: '确认操作',
      content: '确定将所有消息标记为已读吗？',
      confirmColor: '#4a8eff',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' });
          
          // 提供触觉反馈
          if (wx.vibrateShort) {
            wx.vibrateShort({ type: 'light' });
          }
          
          // TODO: 此处应添加实际的标记已读API调用
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '已全部标记为已读',
              icon: 'success'
            });
            
            // 模拟已读效果，移除新消息标记
            const { interactions, combinedInteractions } = this.data;
            if (interactions.likes) {
              interactions.likes.forEach(item => {
                item.isNew = false;
              });
            }
            
            if (interactions.collects) {
              interactions.collects.forEach(item => {
                item.isNew = false;
              });
            }
            
            // 更新合并列表中的新消息标记
            if (combinedInteractions) {
              combinedInteractions.forEach(item => {
                item.isNew = false;
              });
            }
            
            this.setData({ 
              interactions,
              combinedInteractions
            });
          }, 800);
        }
      }
    });
  },

  // 跳转到帖子详情
  goToPostDetail: function(e) {
    const postId = e.currentTarget.dataset.postId;
    wx.navigateTo({
      url: `/pages/details/details?id=${postId}`
    });
  },

  // 跳转到用户主页
  goToUserProfile: function(e) {
    const userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `/pages/user/user?id=${userId}`
    });
  },
  
  // 隐藏筛选框，当点击页面其他区域时
  hideFilter: function() {
    if (this.data.showFilter) {
      this.setData({ showFilter: false });
    }
  },

  // 处理合并后的互动数据
  generateCombinedInteractions: function() {
    const { interactions, currentTab } = this.data;
    let combinedData = [];
    
    // 根据当前标签页确定需要合并的数据
    if (currentTab === 0) {
      // 全部标签页：合并点赞和收藏
      const likesWithType = interactions.likes.map(item => ({
        ...item,
        type: 'like'
      }));
      
      const collectsWithType = interactions.collects.map(item => ({
        ...item,
        type: 'collect'
      }));
      
      // 合并数据
      combinedData = [...likesWithType, ...collectsWithType];
      
      // 按时间排序（降序）
      combinedData.sort((a, b) => {
        const timeA = new Date(a.createTime).getTime();
        const timeB = new Date(b.createTime).getTime();
        return timeB - timeA; // 降序排序
      });
    } else if (currentTab === 1) {
      // 点赞标签页：只包含点赞数据
      combinedData = interactions.likes.map(item => ({
        ...item,
        type: 'like'
      }));
    } else if (currentTab === 2) {
      // 收藏标签页：只包含收藏数据
      combinedData = interactions.collects.map(item => ({
        ...item,
        type: 'collect'
      }));
    }
    
    return combinedData;
  }
}) 